import request from '@/api/request';
import { AxiosPromise } from 'axios';
import {
  CaptchaResult,
  LoginData,
  LoginResult,
  SendEmailCaptchaParam,
  EmailLoginData,
  QQLoginData,
  QQCallbackParams,
  GithubCallbackParams
} from './types';

/**
 * 登录API
 *
 * @param data {LoginData}
 * @returns
 */
export function loginApi(data: LoginData): AxiosPromise<LoginResult> {
  return request({
    url: '/api/v1/auth/login',
    method: 'post',
    data
  });
}

/**
 * 注销API
 */
export function logoutApi() {
  return request({
    url: '/api/v1/auth/logout',
    method: 'delete'
  });
}

/**
 * 获取验证码
 */
export function getCaptchaApi(): AxiosPromise<CaptchaResult> {
  return request({
    url: '/api/v1/auth/captcha',
    method: 'get'
  });
}

/**
 * 发送邮箱验证码
 */
export function sendEmailCaptcha(queryParams: SendEmailCaptchaParam) {
  return request({
    url: '/api/v1/auth/send-email:captcha',
    method: 'get',
    params: queryParams
  });
}

/**
 * 邮箱登录API
 *
 * @param data {LoginData}
 * @returns
 */
export function emailLoginApi(data: EmailLoginData): AxiosPromise<LoginResult> {
  const formData = new FormData();
  formData.append('email', data.email);
  formData.append('captchaKey', data.captchaKey || '');
  formData.append('captchaCode', data.captchaCode || '');
  return request({
    url: '/api/v1/auth/email/login',
    method: 'post',
    data: formData,
    headers: { 'Content-Type': 'multipart/form-data' }
  });
}

/**
 * QQ登录API
 *
 * @param data {LoginData}
 * @returns
 */
export function qqLoginApi(data: QQLoginData): AxiosPromise<LoginResult> {
  const formData = new FormData();
  formData.append('openId', data.openId);
  formData.append('userInfo', data.userInfo);
  return request({
    url: '/api/v1/auth/qq/login',
    method: 'post',
    data: formData,
    headers: { 'Content-Type': 'multipart/form-data' }
  });
}

/**
 * QQ登录回调API
 *
 * @param params QQ回调参数
 * @returns
 */
export function qqLoginCallbackApi(params: QQCallbackParams): AxiosPromise<LoginResult> {
  return request({
    url: '/api/v1/auth/qq/callback',
    method: 'get',
    params
  });
}

/**
 * GitHub登录回调API
 *
 * @param params GitHub回调参数
 * @returns
 */
export function githubLoginCallbackApi(params: GithubCallbackParams): AxiosPromise<LoginResult> {
  return request({
    url: '/api/v1/auth/github/callback',
    method: 'get',
    params
  });
}

export function refreshTokenApi(): AxiosPromise<{
  tokenType: string;
  accessToken: string;
}> {
  return request({
    url: '/api/v1/auth/refresh-token',
    method: 'post',
    withCredentials: true
  });
}
